package com.cyj.comment.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cyj.comment.dto.UserDTO;
import com.cyj.comment.utils.RedisConstants;
import com.cyj.comment.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName LoginInterceptor
 * @Description 所有请求都要经过该过滤器。刷新token有效期，只要用户处于登录状态，token就不会过期。
 * @Author chixiaowai
 * @Date 2023/4/4 10:13
 * @Version 1.0
 */

public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、从请求头中获取token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            //没有携带token，放行
            return true;
        }
        //2、通过token获取redis中的用户
        String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
//        String tokenKey = RedisConstants.LOGIN_USER_KEY;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(tokenKey);
        //3、判断用户是否存在
        if (userMap.isEmpty()){
            //不存在放行
            return true;
        }
        //4、将查询到的hash转为UserDTO对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        //5、保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);
        //6、刷新token有效期
        stringRedisTemplate.expire(tokenKey, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
